package com.bestv.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * Created by Henry on 14-7-14.
 */
public class UpdateTime {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private Resource configFile;
    private Properties timeProperties = null;

    public synchronized String getProperty(String key) {
        timeProperties = new Properties();
        try {
            File file = configFile.getFile();
            if (file.exists()) timeProperties.load(configFile.getInputStream());
        } catch (IOException e) {
            logger.error("Error on IO.", e);
        }
        String time = timeProperties.getProperty(key);
        return time == null ? "19700101000000" : time;
    }

    public synchronized void setProperty(String key, String value) {
        timeProperties.put(key, value);
        try {
            File file = configFile.getFile();
            FileOutputStream out = new FileOutputStream(file);
            timeProperties.store(out, "C2offline update time file");
            out.close();
        } catch (FileNotFoundException e) {
            logger.error("File not found.", e);
        } catch (IOException e) {
            logger.error("Error on IO.", e);
        }
    }

    public Resource getConfigFile() {
        return configFile;
    }

    public void setConfigFile(Resource configFile) {
        this.configFile = configFile;
    }
}
